package com.small.common;

import com.small.util.PropertiesUtil;
import redis.clients.jedis.*;
import redis.clients.util.Hashing;
import redis.clients.util.Sharded;

import java.util.ArrayList;
import java.util.List;

/**
 * @create: xie
 */
public class RedisShardedPool {
    private static ShardedJedisPool pool;//sharded jedis连接池
    private static Integer maxTotal = PropertiesUtil.getIntegerProperty("redis.max.total", 20);//最大连接数
    private static Integer maxIdle = PropertiesUtil.getIntegerProperty("redis.max.idle", 10);//在jedispool中最大的idle状态（空闲的）的jedis实例的个数
    private static Integer minIdle = PropertiesUtil.getIntegerProperty("redis.min.idle", 2);//在jedispool中最小的idle状态（空闲的）的jedis实例的个数
    private static Boolean testOnBorrow = PropertiesUtil.getBooleanProperty("redis.test.borrow", true);//在Borrow一个jedis实例的时候，是否进行验证操作，如果赋值为true，则得到的jedis实例肯定是可以用的
    private static Boolean testOnReturn = PropertiesUtil.getBooleanProperty("redis.test.return", true);//在Return一个jedis实例的时候，是否进行验证操作，如果赋值为true，则放回的jedis实例肯定是可以用的
    private static Integer port1 = PropertiesUtil.getIntegerProperty("redis1.port");//redis端口
    private static String ip1 = PropertiesUtil.getProperty("redis1.ip");//redisIp
    private static Integer port2 = PropertiesUtil.getIntegerProperty("redis2.port");//redis端口
    private static String ip2 = PropertiesUtil.getProperty("redis2.ip");//redisIp

    private static void initPool() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);

        config.setBlockWhenExhausted(true);

        JedisShardInfo shardInfo1 = new JedisShardInfo(ip1, port1, 1000 * 2);
        JedisShardInfo shardInfo2 = new JedisShardInfo(ip2, port2, 1000 * 2);

        List<JedisShardInfo> jedisShardInfoList = new ArrayList<>(2);
        jedisShardInfoList.add(shardInfo1);
        jedisShardInfoList.add(shardInfo2);
        pool = new ShardedJedisPool(config, jedisShardInfoList, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
    }

    //初始化jedispool
    static {
        initPool();
    }

    //返回jedis实例
    public static ShardedJedis getJedis() {
        return pool.getResource();
    }

}
